/**
 * There are code generation
 */
package com.neusoft.lohas.modules.ivm.web.product;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.neusoft.lohas.common.persistence.Page;
import com.neusoft.lohas.common.persistence.StatusBean;
import com.neusoft.lohas.common.utils.FloatFormat;
import com.neusoft.lohas.common.utils.StringUtils;
import com.neusoft.lohas.common.web.BaseController;
import com.neusoft.lohas.modules.ivm.entity.product.Product;
import com.neusoft.lohas.modules.ivm.entity.product.ProductClassify;
import com.neusoft.lohas.modules.ivm.entity.product.ProductInventoryDetail;
import com.neusoft.lohas.modules.ivm.entity.product.ProductOutDetail;
import com.neusoft.lohas.modules.ivm.entity.purchase.PurchaseDetail;
import com.neusoft.lohas.modules.ivm.entity.purchase.Purchase;
import com.neusoft.lohas.modules.ivm.service.product.ProductClassifyService;
import com.neusoft.lohas.modules.ivm.service.product.ProductInventoryDetailService;
import com.neusoft.lohas.modules.ivm.service.product.ProductOutDetailService;
import com.neusoft.lohas.modules.ivm.service.product.ProductService;
import com.neusoft.lohas.modules.ivm.service.purchase.PurchaseService;

/**
 * 商品库存Controller
 * @author Jackie.Liu
 * @version 2014-11-13
 */
@Controller
@RequestMapping(value = "${adminPath}/ivm/inventory")
public class ProductInventoryController extends BaseController {

	@Autowired
	private ProductService productService;
	@Autowired
	private ProductInventoryDetailService productInventoryDetailService;
	@Autowired
	private ProductOutDetailService productOutDetailService;
	@Autowired
	private ProductClassifyService productClassifyService;
	@Autowired
	private PurchaseService purchaseService;
	
	@ModelAttribute
	public Product get(@RequestParam(required=false) String id) {
		if (StringUtils.isNotBlank(id)){
			return productService.get(id);
		}else{
			return new Product();
		}
	}
	
	/**
	 * 库存管理列表
	 * @param product
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequiresPermissions("ivm:inventory:view")
	@RequestMapping(value = {"list", ""})
	public String list(Product product,
			@RequestParam(value="searchParam", required=false, defaultValue="") String searchParam,   
			@RequestParam(value="oneClassify", required=false, defaultValue="") String oneClassify,   //一级分类
			@RequestParam(value="twoClassify", required=false, defaultValue="") String twoClassify,   //二级分类
			HttpServletRequest request, HttpServletResponse response, Model model) {
		if(product.getStock()==0){//默认查询有库存的记录
			product.setStock(3);
		}
		ProductClassify classify = productClassifyService.get(oneClassify);//一级
		ProductClassify classify_t = productClassifyService.get(twoClassify);//二级
		List<ProductClassify> childList = Lists.newArrayList();;
		if(classify_t != null){
			childList.add(classify_t);
		}
		product.setClassify(classify);
		product.setClassifyList(childList);
        Page<Product> page = productService.find(new Page<Product>(request, response), product, searchParam,"sort#asc",false); 
        model.addAttribute("page", page);
        model.addAttribute("searchParam", searchParam);
        model.addAttribute("oneClassify", oneClassify);
        model.addAttribute("twoClassify", twoClassify);
		return "modules/ivm/pro/productInventoryList";
	}

	/**
	 * 商品入库跳转页面
	 * @param productId
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "showIntoInventory")
	public String showIntoInventory(
			@RequestParam(value="productId", required=false, defaultValue="")String productId,
			@RequestParam(value="purchaseId", required=false, defaultValue="")String purchaseId,//采购指令ID
			HttpServletRequest request, HttpServletResponse response, Model model) {
		ProductInventoryDetail productInventoryDetail = new ProductInventoryDetail();
		if (StringUtils.isNotBlank(productId)) {
			productInventoryDetail.setProduct(productService.get(productId));
		}
		if(StringUtils.isNotBlank(purchaseId)){
			//获取采购指令对应的商品List
			Purchase purchase = purchaseService.get(purchaseId);
			productInventoryDetail.setPurchase(purchase);
			productInventoryDetail.setSupplier(purchase.getSupplier());
			productInventoryDetail.setMember(purchase.getMember());
		}
		productInventoryDetail.setMerchant(super.merchant);
		model.addAttribute("productInventoryDetail", productInventoryDetail);
		model.addAttribute("merchant", super.merchant);
		model.addAttribute("purchaseId", purchaseId);
		return "modules/ivm/pro/intoInventory";
	}
	
	/**
	 * 检测商品入库的商品编号是否有效
	 * @param merchantId
	 * @param code
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "checkProductCode")
	public @ResponseBody Object checkProductCode(String merchantId, String code, HttpServletRequest request, HttpServletResponse response){
		Product product = productService.getProductByCode(merchantId, code);
		if (product != null && StringUtils.isNotBlank(product.getId())) {
			return new StatusBean<Product>(product, 200, "商品有效.");
		}else {
			return new StatusBean<Product>(product, 400, "商品不存在.");
		}
	}
	
	/**
	 * 商品入库
	 * @param productInventoryDetail
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "createIntoInventory")
	public String createIntoInventory(
			int type,
			ProductInventoryDetail productInventoryDetail,
			Model model, RedirectAttributes redirectAttributes) {
		Product product = productService.getProductByCode(productInventoryDetail.getMerchant().getId(), productInventoryDetail.getProduct().getCode().toString());
		if (product.getStock()==0) {
			product.setStock(productInventoryDetail.getWinWeight());
			product.setStockAmount(productInventoryDetail.getAmount());
		}else {
			product.setStock(product.getStock()+productInventoryDetail.getWinWeight());
			product.setStockAmount(product.getStockAmount()+productInventoryDetail.getAmount());
			product.setMarketPrice(FloatFormat.m2_2(product.getSpecNum()*product.getStockAmount()/product.getStock()));
		}
		productInventoryDetail.setProduct(product);
		productInventoryDetailService.save(productInventoryDetail);
		productService.save(product);
		addMessage(redirectAttributes, "“"+product.getName()+"”商品入库成功");
		//入库成功
		//如果是采购指令入库
		if (productInventoryDetail.getPurchase()!=null && StringUtils.isNotBlank(productInventoryDetail.getPurchase().getId())) {
			//判断入库的该商品是否入库完成，如果完成判断是否该采购指令对应采购商品是否全部完成（全部完成更新采购指令状态为已完成，部分完成更新采购指令状态为部分完成）
			Purchase purchase = purchaseService.get(productInventoryDetail.getPurchase().getId());
//			int finishNum = 0;
//			for (PurchaseDetail bean : purchase.getDetailList()) {
//				if (bean.getStorageNumber()>=bean.getPurchaseNumber()) {
//					finishNum++;
//				}
//			}
//			if (finishNum==purchase.getDetailList().size()) { //如果全部入库完成
//				purchase.setState("2");
//				purchaseService.save(purchase);
//			}else if(finishNum>0) { //部分入库完成
//				purchase.setState("1");
//				purchaseService.save(purchase);
//			}
			productInventoryDetail.setPurchase(purchase);
			productInventoryDetail.setSupplier(purchase.getSupplier());
			productInventoryDetail.setMember(purchase.getMember());
			model.addAttribute("purchaseId", purchase.getId());
		}
		
		model.addAttribute("productInventoryDetail", productInventoryDetail);
		model.addAttribute("merchant", super.merchant);
		model.addAttribute("type", type);
		return "modules/ivm/pro/intoInventory";
	}
	
	/**
	 * 获取商品入库记录列表
	 * @param productId
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "showInventoryDetail")
	public String showInventoryDetail(ProductInventoryDetail productInventoryDetail,
			HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<ProductInventoryDetail> page = productInventoryDetailService.find(new Page<ProductInventoryDetail>(request, response), productInventoryDetail); 
        model.addAttribute("page", page);
        model.addAttribute("productInventoryDetail", productInventoryDetail);
		return "modules/ivm/pro/productInventoryDetailList";
	}
	
	/**
	 * 获取商品出库记录列表
	 * @param productId
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "showOutDetail")
	public String showOutDetail(ProductOutDetail productOutDetail,
			HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<ProductOutDetail> page = productOutDetailService.find(new Page<ProductOutDetail>(request, response), productOutDetail); 
        model.addAttribute("page", page);
        model.addAttribute("productOutDetail", productOutDetail);
		return "modules/ivm/pro/productOutDetailList";
	}
	
	/**
	 * 获取商品进出库记录列表
	 * @return
	 */
	@RequestMapping(value = "showInOrOutDetail_old")
	public String showInOrOutDetail_old(
			ProductInventoryDetail productInventoryDetail,
			ProductOutDetail productOutDetail,
			@RequestParam(value="productId", required=false, defaultValue="")String productId,
			HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<ProductInventoryDetail> pageIn = productInventoryDetailService.find(new Page<ProductInventoryDetail>(request, response), productInventoryDetail); 
        model.addAttribute("pageIn", pageIn);
        model.addAttribute("productInventoryDetail", productInventoryDetail);
		Page<ProductOutDetail> pageOut = productOutDetailService.find(new Page<ProductOutDetail>(request, response), productOutDetail); 
        model.addAttribute("pageOut", pageOut);
        model.addAttribute("productOutDetail", productOutDetail);
		return "modules/ivm/pro/productInOrOutDetailList";
	}
	
	/**
	 * 获取商品进出库记录列表
	 * @return
	 */
	@RequestMapping(value = "showInOrOutDetail")
	public String showInOrOutDetail(
			ProductInventoryDetail productInventoryDetail,
			ProductOutDetail productOutDetail,
			@RequestParam(value="productId", required=false, defaultValue="")String productId,
			@RequestParam(value="startDate", required=false, defaultValue="")String startDate,
			@RequestParam(value="endDate", required=false, defaultValue="")String endDate,
			HttpServletRequest request, HttpServletResponse response, Model model) {
		//出入库数据
        Page<Map<String, Object>> page = productOutDetailService.findInOut(new Page<Map<String, Object>>(), productId, startDate, endDate);
        int endTock = 0;
        int orderNo = 0;
        for(Map<String, Object> map: page.getList()){
        	map.put("order",orderNo++);
        	map.put("stock",endTock);
        	endTock += Integer.valueOf(map.get("inNum").toString())-Integer.valueOf(map.get("outNum").toString());
        	map.put("endTock", endTock);
        	if(map.get("inNum").toString().equals("0")){
        		map.put("inNum", "");
        	}
        	if(map.get("outNum").toString().equals("0")){
        		map.put("outNum", "");
        	}
        	if(map.get("inOrOut").toString().equals("1")){
        		map.put("outType", "入库");
        	}
        	if(map.get("inOrOut").toString().equals("2")){
        		if(map.get("outType").toString().equals("0")){
        			map.put("outType", "正常出库");
        		}else if(map.get("outType").toString().equals("1")){
        			map.put("outType", "市场支出");
        		}else if(map.get("outType").toString().equals("2")){
        			map.put("outType", "客户退订");
        		}else if(map.get("outType").toString().equals("3")){
        			map.put("outType", "采购损耗");
        		}else{
        			map.put("outType", "");
        		}
        	}
        }
        //倒序排列
        List<Map<String, Object>> descList = new ArrayList<Map<String,Object>>();
        for(int i=page.getList().size()-1;i>=0;i--){
        	descList.add(page.getList().get(i));
        }
        page.setList(descList);
        model.addAttribute("page", page);
		return "modules/ivm/pro/productInOrOutDetailList";
	}
	
	/**
	 * 商品出库跳转页面
	 * @param productId
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "showOutInventory")
	public String showOutInventory(
			@RequestParam(value="productId", required=false, defaultValue="")String productId,
			HttpServletRequest request, HttpServletResponse response, Model model) {
		ProductOutDetail productOutDetail = new ProductOutDetail();
		if (StringUtils.isNotBlank(productId)) {
			productOutDetail.setProduct(productService.get(productId));
		}
		productOutDetail.setMerchant(super.merchant);
		model.addAttribute("productOutDetail", productOutDetail);
		model.addAttribute("merchant", super.merchant);
		return "modules/ivm/pro/outInventory";
	}
	
	/**
	 * 创建商品出库记录
	 * @param productOutDetail
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "createOutInventory")
	public String createOutInventory(
			ProductOutDetail productOutDetail,
			Model model, RedirectAttributes redirectAttributes) {
		Product product = productService.getProductByCode(productOutDetail.getMerchant().getId(), productOutDetail.getProduct().getCode().toString());
			product.setStock(product.getStock()-productOutDetail.getWeight());
			product.setStockAmount(product.getStockAmount()-productOutDetail.getAmount());
			product.setMarketPrice(FloatFormat.m2_2(product.getSpecNum()*product.getStockAmount()/product.getStock()));
			productOutDetail.setProduct(product);
		productOutDetailService.save(productOutDetail);
		productService.save(product);
		addMessage(redirectAttributes, "“"+product.getName()+"”商品出库成功");
		//出库成功
		model.addAttribute("productOutDetail", productOutDetail);
		model.addAttribute("type", "success");
		return "modules/ivm/pro/outInventory";
	}
}
